package com.hyts.network.service.bio;


import com.hyts.network.core.Client;
import com.hyts.network.error.ConnectionException;

import java.io.*;
import java.net.Socket;

/**
 * project-name:coffice-ext-network
 * package-name:com.hyts.ext.network.service
 * author:Libo/Alex
 * create-date:2018-11-24 10:06
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: bio服务操作传参 和 出参
 */
public abstract class BioClient<P,R> extends Client<P,R,Socket> {


    public BioClient(String ip, int port) {
        super(ip, port);
        try {
            this.setClient(new Socket(ip,port));
        } catch (IOException e) {
            throw new ConnectionException("构建客户端失败",e);
        }
    }

    public BioClient() {
        super();
        try {
            this.setClient(new Socket(this.getIp(),this.getPort()));
        } catch (IOException e) {
            throw new ConnectionException("构建客户端失败",e);
        }
    }

    public BioClient(Socket client) {
        super(client);
    }


    public boolean close(){
        if(this.getClient() != null){
            try {
                this.getClient().close();
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    public R execute(P param) {
        try (
                DataOutputStream outputStream = new DataOutputStream(this.getClient().getOutputStream());
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        ){
            objectOutputStream.writeObject(param);
            objectOutputStream.flush();
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.flush();
            return receive();
        } catch (IOException | ClassNotFoundException e ) {
            throw new ConnectionException("操作客户端信息失败！",e);
        }
    }

     @SuppressWarnings("unchecked")
	R receive() throws ClassNotFoundException {
        try (
                DataInputStream inputStream = new DataInputStream(this.getClient().getInputStream());
                ObjectInputStream reader = new ObjectInputStream(inputStream);
        ){
            return (R) reader.readObject();
        } catch (IOException e) {
            throw new ConnectionException("读取客户端信息失败！",e);
        }
    }
}
